package com.lingyi.framework.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lingyi.common.config.WechatConfig;
import com.lingyi.common.constant.CacheConstants;
import com.lingyi.common.core.redis.RedisCache;
import com.lingyi.common.utils.RestTemplateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

/**
 * @PackageName: com.lingyi.framework
 * @ClassName: InitWechat
 * @Description:
 * @Author: czl
 * @Date: 2025/4/19 17:06
 */
@Component
@RequiredArgsConstructor
public class InitWechat implements ApplicationListener<ContextRefreshedEvent> {

    private final WechatConfig wechatConfig;
    private final RestTemplateUtil restTemplateUtil;
    private final RedisCache redisCache;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ResponseEntity<String> exchange = restTemplateUtil.sendGetRequest(wechatConfig.getAccessTokenUrl());
        if (exchange.getStatusCode().is2xxSuccessful()) {
            String body = exchange.getBody();
            JSONObject jsonObject = JSON.parseObject(body);
            redisCache.setCacheObject(CacheConstants.ACCESS_TOKEN_KEY, jsonObject.getString("access_token"));
        }
    }
}
